package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleHtmlTask;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.jws.Oneway;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-31
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {


    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    private ArticleHtmlTask articleHtmlTask;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 保存文章信息
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        //1.判断文章ID是否有值
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto, article);
        if (dto != null) {
            if (dto.getId() == null) {
                //2.如果ID没值 执行新增
                //2.1 新增文章信息
                this.save(article);
                ApArticleContent apArticleContent = new ApArticleContent();
                //2.2 新增文章内容
                apArticleContent.setArticleId(article.getId());
                apArticleContent.setContent(dto.getContent());
                contentService.save(apArticleContent);
            } else {
                //3.如果ID有值 执行修改
                //3.1 修改文章信息
                this.updateById(article);
                //3.2 修改文章内容
                LambdaUpdateWrapper<ApArticleContent> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(ApArticleContent::getContent, dto.getContent());
                updateWrapper.eq(ApArticleContent::getArticleId, dto.getId());
                contentService.update(updateWrapper);
            }
            //3. TODO 生成文章静态化html文件
            articleHtmlTask.createHtmlUpload(article.getId());
            //TODO 将文章信息同步存入ES索引库

            return ResponseResult.okResult(article.getId());
        }
        return ResponseResult.okResult(null);
    }


    /**
     * 分页加载文章列表
     *
     * @param dto  入参查询条件
     * @param type 操作类型：  0：下拉加载最新   1：上拉加载更多数据
     * @return
     */
    @Override
    public ResponseResult loadArticle(ArticleHomeDto dto, int type) {
        //TODO 该接口提供给后台管理调用，以及前端APP调用（存在问题，数据直接从数据库加载存在风险）
        if (dto.getLoaddir().equals(1)) {
            //说明是APP首页获取，直接从redis查询即可
            String redisKey = "leadnews:article:hot:page:" + dto.getChannelId();
            long start = 0;
            long end = 30;
            Set<String> strings = redisTemplate.opsForZSet().reverseRange(redisKey, start, end);
            if (!CollectionUtils.isEmpty(strings)) {
                List<ApArticle> list = strings.stream().map(articleStr -> {
                    ApArticle article = JSON.parseObject(articleStr, ApArticle.class);
                    return article;
                }).collect(Collectors.toList());
                Integer total = list.size();
                return new PageResponseResult(1L, dto.getSize(), total.longValue(), list);
            }

        }

        //1.构建分页对象
        IPage<ApArticle> page = new Page<>(1, dto.getSize());

        //2.构建查询条件
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        //2.1 设置频道条件
        if (ObjectUtils.isNotEmpty(dto.getChannelId())) {
            queryWrapper.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        //2.2 设置排序
        queryWrapper.orderByDesc(ApArticle::getPublishTime);

        //2.3 设置时间条件
        if (type == 0) {
            //下拉加载最新  查询数据库中大于本页第一条记录发布时间
            queryWrapper.gt(ApArticle::getPublishTime, dto.getMaxTime());
        } else {
            //上拉加载更多  查询数据库小于本页最后一条记录发布时间
            queryWrapper.lt(ApArticle::getPublishTime, dto.getMinTime());
        }
        //2.4 未删除 未下架
        queryWrapper.eq(ApArticle::getIsDelete, false);
        queryWrapper.eq(ApArticle::getIsDown, false);

        //3.执行查询
        this.page(page, queryWrapper);

        //4.封装响应分页结果
        return new PageResponseResult(1L, dto.getSize(), page.getTotal(), page.getRecords());
    }

    /**
     * 查询文章详情:从数据库中获取存在风险
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        //1.根据文章ID查询文章信息
        ApArticle article = this.getById(dto.getArticleId());
        if (article == null || article.getIsDelete() || article.getIsDown()) {
            return ResponseResult.errorResult(400, "文章不存在！");
        }
        //2.根据文章ID查询文章内容
        LambdaQueryWrapper<ApArticleContent> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent content = contentService.getOne(queryWrapper);


        //3.封装响应结果
        HashMap<String, Object> mapResult = new HashMap<>();
        mapResult.put("config", article);
        mapResult.put("content", content);
        return ResponseResult.okResult(mapResult);
    }
}
